package com.ruoyi.bellItem.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.bellItem.domain.ClockItem;
import com.ruoyi.bellItem.mapper.ClockItemMapper;
import com.ruoyi.bellItem.service.IClockItemService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.check.CheckEmptyUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.routineItem.mapper.ItemMapper;
import com.ruoyi.vo.AddTechnicianVo;
import com.ruoyi.vo.SelectTechnicianListResponseVo;
import com.ruoyi.vo.SelectTechnicianListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 加钟服务项目Controller
 *
 * @author ruoyi
 * @date 2025-04-07
 */
@RestController
@RequestMapping("/clockItem/clockItem")
public class ClockItemController extends BaseController {
    @Autowired
    private IClockItemService clockItemService;
    @Resource
    private ClockItemMapper clockItemMapper;
    @Resource
    private ItemMapper itemMapper;

    /**
     * 查询加钟服务项目列表
     */
    @PreAuthorize("@ss.hasPermi('clockItem:clockItem:list')")
    @GetMapping("/list")
    public TableDataInfo list(ClockItem clockItem) {
        startPage();
        List<ClockItem> list = clockItemService.selectClockItemList(clockItem);
        return getDataTable(list);
    }

    /**
     * 导出加钟服务项目列表
     */
    @PreAuthorize("@ss.hasPermi('clockItem:clockItem:export')")
    @Log(title = "加钟服务项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ClockItem clockItem) {
        List<ClockItem> list = clockItemService.selectClockItemList(clockItem);
        ExcelUtil<ClockItem> util = new ExcelUtil<ClockItem>(ClockItem.class);
        util.exportExcel(response, list, "加钟服务项目数据");
    }

    /**
     * 获取加钟服务项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('clockItem:clockItem:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(clockItemService.selectClockItemById(id));
    }

    /**
     * 新增加钟服务项目
     */
    @PreAuthorize("@ss.hasPermi('clockItem:clockItem:add')")
    @Log(title = "加钟服务项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ClockItem clockItem) {
        return toAjax(clockItemService.insertClockItem(clockItem));
    }

    /**
     * 修改加钟服务项目
     */
    @PreAuthorize("@ss.hasPermi('clockItem:clockItem:edit')")
    @Log(title = "加钟服务项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ClockItem clockItem) {
        return toAjax(clockItemService.updateClockItem(clockItem));
    }

    /**
     * 删除加钟服务项目
     */
    @PreAuthorize("@ss.hasPermi('clockItem:clockItem:remove')")
    @Log(title = "加钟服务项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(clockItemService.deleteClockItemByIds(ids));
    }

    /**
     * 获取服务关联的技师
     */
    @PreAuthorize("@ss.hasPermi('technician:technician:selectItem')")
    @PostMapping(value = "/selectRelevancyTechnician")
    public AjaxResult selectRelevancyTechnician(@RequestBody SelectTechnicianListVo requestVo) {
        ClockItem clockItem = clockItemMapper.selectClockItemById(requestVo.getItemId());


        if (!CheckEmptyUtil.isEmpty(clockItem.getTid())) {
            String tids = clockItem.getTid();
            List<Long> longs = Arrays.stream(tids.split(",")) // 拆分字符串
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            PageHelper.startPage(requestVo.getPageNum(), requestVo.getPageSize());
            List<SelectTechnicianListResponseVo> serviceItems = itemMapper.selectTechnician(longs);
            return success(new PageInfo<>(serviceItems));
        }
        return success(new PageInfo<>());
    }

    /**
     * 查询项目未关联的技师列表
     */
    @PreAuthorize("@ss.hasPermi('technician:technician:selectItem')")
    @PostMapping(value = "/selectTechnicianList")
    public AjaxResult selectTechnicianList(@RequestBody SelectTechnicianListVo requestVo) {
        // 获取所有Technician的ID
        List<Long> list2 = itemMapper.selectAllTid();

        List<Long> result = new ArrayList<>();
        ClockItem clockItem = clockItemMapper.selectClockItemById(requestVo.getItemId());
        if (clockItem == null || clockItem.getTid() == null) {
            result =list2; // 如果Item不存在或tid为空，返回所有Technician
        }

        if (!CheckEmptyUtil.isEmpty(clockItem.getTid())) {

            Set<Long> tidSet = Arrays.stream(clockItem.getTid().split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            // 找出不包含在tid列表中的Technician ID
            Set<Long> allTids = new HashSet<>(list2);
            // 使用Stream过滤list2，去除list1中的元素
            result = allTids.stream()
                    .filter(tid -> !tidSet.contains(tid))
                    .collect(Collectors.toList());
        }

        PageHelper.startPage(requestVo.getPageNum(), requestVo.getPageSize());
        List<SelectTechnicianListResponseVo> technicianList = clockItemMapper.selectTechnicianList(requestVo.getKeyWord(), result);

        return success(new PageInfo<>(technicianList));
    }


    /**
     * 关联技师
     */
    @PreAuthorize("@ss.hasPermi('technician:technician:selectItem')")
    @PostMapping(value = "/addTechnician")
    public AjaxResult addTechnician(@RequestBody AddTechnicianVo requestVo) {
        // 使用Stream API将列表转换为逗号拼接的字符串
        String tids = requestVo.getTids().stream()
                .map(String::valueOf) // 将Long转换为String
                .collect(Collectors.joining(",")); // 使用逗号连接字符串
        Integer updateItem = clockItemMapper.addTechnician(requestVo.getItemId(), tids);
        return success(updateItem);
    }


    /**
     * 取消技师关联
     */
    @PreAuthorize("@ss.hasPermi('technician:technician:selectItem')")
    @PostMapping(value = "/updateTechnician")
    public AjaxResult updateTechnician(@RequestBody AddTechnicianVo requestVo) {
        ClockItem clockItem = clockItemMapper.selectClockItemById(requestVo.getItemId());
        String tids = clockItem.getTid();
        Long tid = requestVo.getTid();
        tids = removeItemFromServiceItem(tids, tid);
        Integer updateItem = clockItemMapper.updateTechnician(requestVo.getItemId(), tids);
        return success(updateItem);
    }

    // 在TechnicianController.java中添加以下方法
    public String removeItemFromServiceItem(String serviceItem, Long itemId) {
        String itemIdStr = String.valueOf(itemId);

        // 如果字符串中只有一个数字，且等于要删除的数字
        if (serviceItem.equals(itemIdStr)) {
            return "";
        }

        // 如果要删除的数字后面有逗号（包括位于开头和中间的情况）
        if (serviceItem.startsWith(itemIdStr + ",")) {
            // 如果要删除的数字位于开头
            if (serviceItem.length() == itemIdStr.length() + 1) {
                // 只有一个数字和逗号，删除后变为空字符串
                return "";
            } else {
                // 删除数字及其后面的逗号
                return serviceItem.substring(itemIdStr.length() + 1);
            }
        } else if (serviceItem.contains("," + itemIdStr + ",")) {
            // 如果要删除的数字位于中间
            int startIndex = serviceItem.indexOf("," + itemIdStr + ",");
            return serviceItem.substring(0, startIndex) + "," + serviceItem.substring(startIndex + itemIdStr.length() + 2);
        } else if (serviceItem.endsWith("," + itemIdStr)) {
            // 如果要删除的数字位于末尾，且前面有逗号
            return serviceItem.substring(0, serviceItem.length() - itemIdStr.length() - 1);
        } else if (serviceItem.endsWith(itemIdStr) && !serviceItem.endsWith("," + itemIdStr)) {
            // 如果要删除的数字位于末尾，且后面没有逗号
            return serviceItem.substring(0, serviceItem.length() - itemIdStr.length());
        }

        // 如果要删除的数字不存在于字符串中，返回原字符串
        return serviceItem;
    }
}
